package com.wan37.logic.dao.impl;

import com.wan37.logic.dao.UserWeaponryDao;
import com.wan37.logic.domain.entity.UserWeaponryDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-06-17 14:49
 **/
@Transactional(propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = Exception.class)
@Repository
public class UserWeaponryDaoImpl implements UserWeaponryDao {

    @Autowired
    HibernateTemplate hibernateTemplate;

    @Override
    public boolean add(UserWeaponryDO userWeaponryDO) {
        try {
            hibernateTemplate.save(userWeaponryDO);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(Integer id) {
        try {
            hibernateTemplate.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean update(UserWeaponryDO userWeaponryDO) {
        try {
            Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            Query query = session.createQuery("update UserWeaponryDO u set u.level=?, u.durability=?, u.usage=? where u.userId=? and u.selfWeaponryId=?");
            query.setParameter(0, userWeaponryDO.getLevel());
            query.setParameter(1, userWeaponryDO.getDurability());
            query.setParameter(2, userWeaponryDO.getUsage());
            query.setParameter(3, userWeaponryDO.getUserId());
            query.setParameter(4, userWeaponryDO.getSelfWeaponryId());
            query.executeUpdate();
            session.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<UserWeaponryDO> getAll() {
        return null;
    }

    @Override
    public List<UserWeaponryDO> getUserWeaponryDOByUserId(String userId) {
        return (List<UserWeaponryDO>) hibernateTemplate.find("from UserWeaponryDO where userId = ?", userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBySelfWeaponryId(String selfWeaponryId) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("delete from UserWeaponryDO where selfWeaponryId = ?");
        query.setParameter(0,  selfWeaponryId);
        query.executeUpdate();
        return true;
    }
}
